package com.nb.protocol.service;

import com.nb.protocol.protocol.MessageHolder;
import com.nb.protocol.protocol.ProtocolHeader;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.concurrent.Future;
import org.apache.log4j.Logger;

/**
 * @function:
 * @author: hjw
 * @date: 2018/1/8
 * @company: Sinoregal
 * @copyright: 2018 www.sinoregal.cn. All rights reserved.
 */
public abstract class BaseSesorService {
    private static final Logger logger = Logger.getLogger(BaseSesorService.class);
    protected void success(MessageHolder messageHolder) {
        Future future = null;
        try {
            future = sendResponse(messageHolder, ProtocolHeader.SUCCESS);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        sendResponse(messageHolder,ProtocolHeader.SUCCESS);
                    }
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    protected void fail(MessageHolder messageHolder) {
        Future future = null;
        try {
            future = sendResponse(messageHolder, ProtocolHeader.SERVER_ERROR);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        sendResponse(messageHolder,ProtocolHeader.SERVER_ERROR);
                    }
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private Future sendResponse(MessageHolder messageHolder,byte state) throws InterruptedException {
        MessageHolder messageHolder2 = new MessageHolder();
        messageHolder2.setRemoteAddr(messageHolder.getRemoteAddr());
        messageHolder2.setCpuId(messageHolder.getCpuId());
        messageHolder2.setCpuIdBytes(messageHolder.getCpuIdBytes());
        messageHolder2.setSerial(messageHolder.getSerial());
        messageHolder2.setType(messageHolder.getType());
        messageHolder2.setFrame((short)(messageHolder.getFrame()<<8));
        messageHolder2.setSender(messageHolder.getSender());
        byte[] bytes = new byte[]{state};
        messageHolder2.setBody(bytes);
        Future future = null;
        logger.info("开始回复数据:"+messageHolder2.toString());
        future =  messageHolder.getChannel().writeAndFlush(messageHolder2);
        logger.info("回复数据结束");
        return  future;
    }
}
